package com.gcloud.mesh.framework.core.mq;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.scheduling.annotation.Scheduled;

import com.gcloud.mesh.header.exception.BaseException;
import com.gcloud.mesh.header.exception.CommonErrorCode;
import com.gcloud.mesh.header.msg.MqBaseMsg;

public class SyncReplyMsgs {

    private static final Map<String, MqBaseMsg> REPLY_MSGS = new ConcurrentHashMap<>();

    public static MqBaseMsg waitForReply(String msgId, int timeoutInSecodes) throws BaseException {
        int restTime = timeoutInSecodes * 1000;
        while (true) {
            if (restTime <= 0) {
                throw new BaseException(CommonErrorCode.SYNC_MSG_TIMEOUT);
            }
            restTime -= 500;
            try {
                Thread.sleep(500);
            }
            catch (InterruptedException e) {

            }

            MqBaseMsg reply = REPLY_MSGS.remove(msgId);
            if (reply != null) {
                return reply;
            }
        }
    }

    public static void addReply(MqBaseMsg reply) {
        REPLY_MSGS.put(reply.getMsgId(), reply);
    }

    @Scheduled(initialDelay = 30, fixedDelay = 30 * 1000)
    void periodClear() {
        List<String> caches = new ArrayList<>();
        for (String msgId : REPLY_MSGS.keySet()) {
            caches.add(msgId);
        }

        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {

        }

        for (String msgId : caches) {
            REPLY_MSGS.remove(msgId);
        }
    }
}
